//
//  YUYAAllAreaListTableView.m
//  com.yigu.yuya
//
//  Created by hxp on 16/3/9.
//  Copyright © 2016年 hxp. All rights reserved.
//  城市列表

#import "YAYIAllAreaListTableView.h"
#import "YAYIAllAreaListCell.h"
//#import "YAYIAppointhospitallController.h"
#import "YAYIAreaListViewController.h"

@interface YAYIAllAreaListTableView()

// 热门地区列表
@property (nonatomic, strong) NSMutableArray *hotAreaArray;


@property (nonatomic, copy) NSString *areaName;
@property (nonatomic, copy) NSString *areaCode;
@end


@implementation YAYIAllAreaListTableView


- (NSMutableArray *)hotAreaArray
{
    if(nil == _hotAreaArray){
//        _hotAreaArray = [[NSArray alloc] init];
        _hotAreaArray = [NSMutableArray arrayWithArray:@[@{@"id":@(0), @"name":@"全国"},
//                          @{@"id":@(330100), @"name":@"杭州市"},
                          @{@"id":@(31), @"name":@"上海市"},
                          @{@"id":@(11), @"name":@"北京市"},
                          @{@"id":@(440100), @"name":@"广州市"},
                          @{@"id":@(420100), @"name":@"武汉市"},
                          @{@"id":@(320100), @"name":@"南京市"},
                          @{@"id":@(430100), @"name":@"长沙市"},
                        @{@"id":@(330100), @"name":@"杭州市"},
                          @{@"id":@(370200), @"name":@"青岛市"},
                          ]];
        
        // 得到当前城市
        NSDictionary *locDict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:YAYILocationKey];
        
        if (locDict) {
            NSString *cityTitle = locDict[@"locality"];
            NSString *areaCode = locDict[@"areacode"];
            NSDictionary *curLocDict = @{@"id":areaCode, @"name":cityTitle};
            
            // 去除重复
            [_hotAreaArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj[@"name"] isEqualToString:cityTitle]) {
                    [_hotAreaArray removeObjectAtIndex:idx];
                    *stop = YES;
                }
            }];
            
            [_hotAreaArray insertObject:curLocDict atIndex:1];
        }
        
        
    }
    return _hotAreaArray;
}

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.dataAry = [NSMutableArray  array];
        self.backgroundColor = [UIColor orangeColor];
        [self createTableView:frame];
    }
    return self;
}

-(void)createTableView:(CGRect)recrt;
{
    if (self.allAreaListTableView == nil) {
        self.allAreaListTableView = [[UITableView alloc] init];
        self.allAreaListTableView.backgroundColor = [UIColor whiteColor];
        self.allAreaListTableView.dataSource = self;
        self.allAreaListTableView.delegate = self;
        self.allAreaListTableView.tag = 1002;
        self.allAreaListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.allAreaListTableView.showsVerticalScrollIndicator = NO;
        [self addSubview:self.allAreaListTableView];
    }
    if (recrt.size.height == 0) {
        [self.allAreaListTableView  mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@0);
            make.top.equalTo(@0);
            make.width.equalTo(@((1 - 0.427)*SCREEN_width));
            make.bottom.equalTo(self.mas_bottom);
//            make.size.mas_equalTo(CGSizeMake((1 - 0.427)*SCREEN_width , SCREEN_height));
        }];
    }else{
        [self.allAreaListTableView  mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@0);
            make.top.equalTo(@0);
            make.size.mas_equalTo(CGSizeMake((1 - 0.427)*SCREEN_width , SCREEN_height/2.0));
        }];
    }
    
}
-(void)setMyViewController:(UIViewController *)viewController
{
    self.viewController = viewController;
}


-(void)createDataSource:(NSString *)areaCode areaName:(NSString *)areaName
{
    self.areaName = areaName;
    self.areaCode = areaCode;
    
    
    if ([areaCode isEqualToString:@""]) {
        [self.dataAry  removeAllObjects];
        [self.allAreaListTableView reloadData];
        return;
    }
    if (self.dataAry.count >0) {
        [self.dataAry  removeAllObjects];
        [self.allAreaListTableView  reloadData];
        
    }
    
    if (0 == [areaCode integerValue]) {
        [self.dataAry addObjectsFromArray:self.hotAreaArray];
        [self.allAreaListTableView  reloadData];
        return;
    }
    
    [YAYINetWorking getWithURL:all_local_city_url param:@{@"id":areaCode} finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            NSArray *data = dict[@"data"];
            
            NSDictionary *allAreaDict = @{@"id":areaCode, @"name":@"不限"};
            [self.dataAry addObject:allAreaDict];
//            [self.dataAry addObject:@"不限"];
            for (NSDictionary *dic in data) {
                NSString *areaStr = dic[@"name"];
                if ([areaStr isEqualToString:areaName] || [areaStr isEqualToString:@"市辖区"] || [areaStr isEqualToString:@"县"]) {
                    continue;
                }
                [self.dataAry addObject:dic];
            }
            [self.allAreaListTableView  reloadData];
        }

    }];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indefiter = @"cell";
    YAYIAllAreaListCell *cell = [tableView  dequeueReusableCellWithIdentifier:indefiter];
    if (cell == nil) {
        cell = [[ YAYIAllAreaListCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:indefiter];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *dict = _dataAry[indexPath.row];
    
    // 得到当前城市
    NSDictionary *locDict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:YAYILocationKey];
    
    if (locDict && [self.areaCode integerValue] == 0 && [locDict[@"locality"] isEqualToString:dict[@"name"]])
    {
        // 后面加上“（自动定位）”
        NSString *cityNameStr = [NSString stringWithFormat:@"%@（自动定位）", dict[@"name"] ];
        NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:cityNameStr];
        NSDictionary *attri = @{NSForegroundColorAttributeName:YAYIColor(180, 180, 180), NSFontAttributeName:[UIFont systemFontOfSize:13]};
        NSRange range = NSMakeRange(cityNameStr.length - 6, 6);
        [attriStr addAttributes:attri range:range];
        
        cell.local.attributedText = attriStr;
        
    }else{
        cell.local.text = dict[@"name"];
    }
    
    return cell;

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataAry.count;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.lastCell.backgroundColor = [UIColor whiteColor];
    YAYIAllAreaListCell *cell = [tableView  cellForRowAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithWhite:0.965 alpha:1];
    self.lastCell = cell;
    NSDictionary *dict = self.dataAry[indexPath.row];
    
    if (_delegate && [_delegate respondsToSelector:@selector(countryCode:countryName:)]) {
        NSString *areaName = dict[@"name"];
        if ([areaName isEqualToString:@"不限"]) {
            areaName = self.areaName;
        }
        
        [_delegate countryCode:dict[@"id"] countryName:areaName];
    }
}

//-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    UIView *headerView = [UIView  new];
//    headerView.backgroundColor = [UIColor whiteColor];
//    self.titleLabel.userInteractionEnabled = YES;
//    self.titleLabel = [UILabel new];
//    self.titleLabel.text = self.title;
//    self.titleLabel.font = [UIFont systemFontOfSize:font16];
//    self.titleLabel.textColor  = [UIColor colorWithRed:87/255.0 green:85/255.0 blue:85/255.0 alpha:1];
//    [headerView addSubview:self.titleLabel];
//    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(@50);
//        make.centerY.mas_equalTo(headerView.mas_centerY);
//        make.right.equalTo(@10);
//    }];
//    [headerView addSubview:self.titleLabel];
//    
//    return headerView;
//}
//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 44;
//}

@end
